package com.strawcom.charmring.ui.fragment;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.litepal.crud.DataSupport;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.strawcom.charmring.App;
import com.strawcom.charmring.BaseFragment;
import com.strawcom.charmring.C;
import com.strawcom.charmring.R;
import com.strawcom.charmring.bean.Calories;
import com.strawcom.charmring.bean.DailySummary;
import com.strawcom.charmring.bluetooth.RingBleService;
import com.strawcom.charmring.ui.MainActivity;
import com.strawcom.charmring.util.AnimUtil;
import com.strawcom.charmring.util.BaseUtil;
import com.strawcom.charmring.util.LogUtil;
import com.strawcom.charmring.util.ViewUtil;
import com.strawcom.charmring.view.ExerciseRerocdLayout;
import com.strawcom.charmring.view.HorizontalWheelView;
import com.strawcom.charmring.view.HorizontalWheelView.OnItemSelectedListener;
import com.strawcom.charmring.view.HorizontalWheelView.OnSlidingStateChangedListener;
import com.strawcom.charmring.view.RiseSlidingLayout;
import com.strawcom.charmring.view.SlidingMenu;
import com.strawcom.charmring.view.WaterCupView;

/**
 * @author WangPeng
 * 
 */
@SuppressLint("SimpleDateFormat")
public class ExerciseDailySummaryFragment extends BaseFragment {

	protected MainActivity holderActivity;

	@Override public void onAttach(Activity activity) {
		super.onAttach(activity);
		if (activity instanceof MainActivity) {
			holderActivity = (MainActivity) activity;
		}
	}

	private final List<DailySummary> dailySummaryList = new ArrayList<DailySummary>();
	private final List<Calories> caloriesList = new ArrayList<Calories>();
	private final List<String> titleList = new ArrayList<String>();

	private int selectedIndex = 0;

	private View imgShare;
	private WaterCupView viewWaterCup;
	private HorizontalWheelView viewTabs;
	private ListView listView;

	private ExerciseRerocdLayout layExerciseRecord;
	private RiseSlidingLayout layRiseSliding;

	private SimpleDateFormat sdfTitleDate;
	private String[] listRecordType;
	
	private TextView txTotalStep, txTotalDist , txTotalDistUnit;
	
	@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_exercise_daily_summary, container, false);

		viewWaterCup = (WaterCupView) view.findViewById(R.id.view_water_cup);
		layRiseSliding = (RiseSlidingLayout) view.findViewById(R.id.lay_rise_sliding);
		viewTabs = (HorizontalWheelView) view.findViewById(R.id.pagerSlidingTabStrip);
		viewTabs.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override public void onItemSelected(int position) {
				selectedIndex = position;
				LogUtil.e("top时期造成查询notifyDataSetChanged!!!");
				notifyDataSetChanged();
			}
		});
		listView = (ListView) view.findViewById(R.id.listView);
		listView.setAdapter(adapter);

		layExerciseRecord = (ExerciseRerocdLayout) view.findViewById(R.id.lay_exercise_record);
		layExerciseRecord.post(new Runnable() {
			@Override public void run() {
				layExerciseRecord.setVisibility(View.INVISIBLE);
			}
		});

		view.findViewById(R.id.view_weight_set).setOnClickListener(new OnClickListener() {
			@Override public void onClick(View v) {
				// 每次都显示对应日期的体重， 只有为今天的时候才可以编辑
				layExerciseRecord.show(dailySummaryList.get(selectedIndex).getWeight(), selectedIndex == dailySummaryList.size() - 1);
			}
		});
		
		imgShare = view.findViewById(R.id.img_share);
		
		imgShare.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// 截屏耗时，避免重复点击设置enabled
				imgShare.setEnabled(false);
				imgShare.postDelayed(new Runnable() {
					@Override public void run() {
						imgShare.setEnabled(true);
					}
				}, 1000);
				
				imgShare.startAnimation(AnimUtil.init()
						.addAlpha(1f, 0.1f, 0, 200, null, Animation.REVERSE)
						.create());
				
				shareToFriend();
			}
		});
		

		TextView txExerciseTip666 = (TextView) view.findViewById(R.id.tx_exercise_tip_666);
		txExerciseTip666.setTypeface(App.i().tfYouYuan);
		
		sdfTitleDate = new SimpleDateFormat(getString(C.exercise.record_title_patttern));
		listRecordType = getResources().getStringArray(R.array.exercise_summary_record_type);
		
		txTotalStep = (TextView) view.findViewById(R.id.tx_total_step);
		txTotalDist = (TextView) view.findViewById(R.id.tx_total_dist);
		txTotalDistUnit = (TextView) view.findViewById(R.id.tx_total_dist_unit);

		// to stop water cup . make sliding smooth..
		makeSlidingSmooth();
		return view;
	}

	@Override public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		registerRingMessageReceiver();

		dailySummaryList.clear();
		dailySummaryList.addAll(DataSupport.order("date asc").find(DailySummary.class));
	}

	@Override public void onDestroy() {
		super.onDestroy();
		unregisterRingMessageReceiver();
	}

	@Override public void onPause() {
		super.onPause();
		viewWaterCup.stopRunWaterAnim();
	}

	@Override public void onResume() {
		super.onResume();
		viewWaterCup.startRunWaterAnim();
		
		layRiseSliding.returnBottom();
		// init exercise summary info
		refreshSummaryInfo();
	}

	private BaseAdapter adapter = new BaseAdapter() {

		@Override public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder viewHolder = null;

			if (convertView != null) {
				viewHolder = (ViewHolder) convertView.getTag();
			}
			else {
				viewHolder = new ViewHolder();
				convertView = LayoutInflater.from(holderActivity).inflate(R.layout.list_content_exercise_record, null);

				viewHolder.layLeft = convertView.findViewById(R.id.lay_record_left);
				viewHolder.layRight = convertView.findViewById(R.id.lay_record_right);
				viewHolder.txTime1 = (TextView) convertView.findViewById(R.id.tx_record_time_1);
				viewHolder.txTime2 = (TextView) convertView.findViewById(R.id.tx_record_time_2);
				viewHolder.txWay1 = (TextView) convertView.findViewById(R.id.tx_record_way_1);
				viewHolder.txWay2 = (TextView) convertView.findViewById(R.id.tx_record_way_2);
				viewHolder.txEnergy1 = (TextView) convertView.findViewById(R.id.tx_record_energy_1);
				viewHolder.txEnergy2 = (TextView) convertView.findViewById(R.id.tx_record_energy_2);
				viewHolder.txStep1 = (TextView) convertView.findViewById(R.id.tx_record_step_1);
				viewHolder.txStep2 = (TextView) convertView.findViewById(R.id.tx_record_step_2);
				viewHolder.txDist1 = (TextView) convertView.findViewById(R.id.tx_record_dist_1);
				viewHolder.txDist2 = (TextView) convertView.findViewById(R.id.tx_record_dist_2);

				ViewUtil.changeFontsStyle(convertView, holderActivity);

				convertView.setTag(viewHolder);
			}

			viewHolder.layLeft.setVisibility(position % 2 == 0 ? View.VISIBLE : View.INVISIBLE);
			viewHolder.txTime1.setVisibility(position % 2 == 0 ? View.VISIBLE : View.INVISIBLE);
			viewHolder.layRight.setVisibility(position % 2 == 0 ? View.INVISIBLE : View.VISIBLE);
			viewHolder.txTime2.setVisibility(position % 2 == 0 ? View.INVISIBLE : View.VISIBLE);

			resetExerciseCaloriesInfo(viewHolder, position);

			return convertView;
		}

		private void resetExerciseCaloriesInfo(ViewHolder viewHolder, int position) {
			final Calories calories = caloriesList.get(position);
			String wayInfo = "";
			if(calories.getDuration() <= 0){
				wayInfo = 
						listRecordType[calories.getType()] + getString(R.string.exercise_record_onemin_1);
			}else {
				wayInfo = calories.getDuration() > 60 ? getString(R.string.exercise_record_way, listRecordType[calories.getType()],
						calories.getDuration() / 60, calories.getDuration() % 60) : getString(R.string.exercise_record_way_1,
						listRecordType[calories.getType()], calories.getDuration() % 60);
				wayInfo = wayInfo.replace(getString(R.string.exercise_record_way_1), "");	
			}
			
			final String energyInfo = getString(R.string.exercise_record_energy, String.format("%.1f", calories.getCalorie()));
			final String stepInfo = getString(R.string.exercise_record_step, calories.getStep());
			final float dist = calories.getDistance();
			final String distInfo = dist > 1000 ? String.format("%.1f", dist / 1000) + getString(R.string.exercise_total_dist_3) : 
					((int)dist) + getString(R.string.exercise_total_dist_2);
			if (position % 2 == 0) {
				viewHolder.txTime1.setText(calories.getRecordTimeInfo());
				viewHolder.txWay1.setText(wayInfo);
				viewHolder.txEnergy1.setText(energyInfo);
				viewHolder.txStep1.setText(stepInfo);
				viewHolder.txDist1.setText(distInfo);
			}
			else {
				viewHolder.txTime2.setText(calories.getRecordTimeInfo());
				viewHolder.txWay2.setText(wayInfo);
				viewHolder.txEnergy2.setText(energyInfo);
				viewHolder.txStep2.setText(stepInfo);
				viewHolder.txDist2.setText(distInfo);
			}
		}

		class ViewHolder {
			View layLeft, layRight;
			TextView txTime1, txTime2, txWay1, txWay2, txEnergy1, txEnergy2, txStep1, txStep2, txDist1, txDist2;
		}

		@Override public long getItemId(int position) {
			return position;
		}

		@Override public Object getItem(int position) {
			return caloriesList.get(position);
		}

		@Override public int getCount() {
			return caloriesList.size();
		}
	};

	private void makeSlidingSmooth() {
		layRiseSliding.setOnSlidingStateChangedListener(new RiseSlidingLayout.OnSlidingStateChangedListener() {
			@Override public void onSlidingStart() {
				viewWaterCup.stopRunWaterAnim();
			}

			@Override public void onSlidingOver(boolean isOpen) {
				if (!isOpen) viewWaterCup.startRunWaterAnim();
				
				// 重新读取运动信息
				if(isOpen && getActivity() instanceof MainActivity){
					MainActivity mainActivity = (MainActivity) getActivity();
					mainActivity.requestExerciseInfo();
				}
			}
		});
		if (holderActivity != null) {
			holderActivity.getSlidingMenu().setOnSlidingStateChangedListener(new SlidingMenu.OnSlidingStateChangedListener() {
				@Override public void onSlidingStart() {
					viewWaterCup.stopRunWaterAnim();
				}

				@Override public void onSlidingOver(boolean isOpen) {
					if (!isOpen) viewWaterCup.startRunWaterAnim();
				}
			});
		}

		viewTabs.setOnSlidingStateChangedListener(new OnSlidingStateChangedListener() {
			@Override public void onSlidingStart() {
				viewWaterCup.stopRunWaterAnim();
			}

			@Override public void onSlidingOver() {
				viewWaterCup.startRunWaterAnim();
			}
		});
	}

	private void refreshSummaryInfo() {
		if(dailySummaryList.size() > 0) {
			final int todayIndex = dailySummaryList.size() - 1;
			if (!dailySummaryList.get(todayIndex).getDate().equals(App.i().getDailySummary().getDate())) {
				initExerciseSummaryInfo();
				return;
			}
			// 更新今天的内容
			dailySummaryList.set(todayIndex, App.i().getDailySummary());
			// init exercise date info by summary info
			notifyTopDateInfoChangedBySummaryInfo();
		}
	}

	/** 顶部时间已经过期。重新查询数据库加载 */
	private void initExerciseSummaryInfo() {
		dailySummaryList.clear();
		dailySummaryList.addAll(DataSupport.order("date asc").find(DailySummary.class));
		// init exercise date info by summary info
		notifyTopDateInfoChangedBySummaryInfo();
	}

	private void notifyDataSetChanged() {
		// init calories list for selected day
		LogUtil.e("notifyDataSetChanged!!!");
		queryCaloriesInfo();

		setWaterValue();
	}

	private void notifyTopDateInfoChangedBySummaryInfo() {
		SimpleDateFormat sdfRecordDate = App.i().getSdfRecordDate();
		Date dailySummaryDate = null;

		if (titleList.size() == dailySummaryList.size() && dailySummaryList.size() > 0) {
			// dailySummaries must be not empty ! control the program logic to
			// avoid this
			DailySummary dailySummary = dailySummaryList.get(0);
			try {
				dailySummaryDate = sdfRecordDate.parse(dailySummary.getDate());
			} catch (ParseException e) {
				e.printStackTrace();
			}
			String date = sdfTitleDate.format(dailySummaryDate);
			if (titleList.get(0).equals(date)) {
				return;
			}
		}

		titleList.clear();
		for (DailySummary dailySummary : dailySummaryList) {
			try {
				dailySummaryDate = sdfRecordDate.parse(dailySummary.getDate());
			} catch (ParseException e) {
				e.printStackTrace();
			}
			String title = App.i().today.equals(dailySummary.getDate()) ? getString(R.string.exercise_today) : sdfTitleDate
					.format(dailySummaryDate);
			titleList.add(title);
		}
		viewTabs.setValueInfo(titleList);
		selectedIndex = titleList.size() - 1;
	}

	private void queryCaloriesInfo() {
		if(selectedIndex >= 0 && selectedIndex < dailySummaryList.size()) {
			DailySummary dailySummary = dailySummaryList.get(selectedIndex);
			caloriesList.clear();
			LogUtil.e("queryCaloriesInfo 耗时操作被调用:");
			caloriesList.addAll(dailySummary.getResultCalories());
			adapter.notifyDataSetChanged();
			
			int totalStep =0 ;
			float totalDist = 0;
			for (Calories c : caloriesList) {
				totalStep += c.getStep();
				totalDist += c.getDistance();
			}
			txTotalStep.setText(String.valueOf(totalStep));
			if(totalDist > 1000) {
				txTotalDist.setText(String.format("%.1f", totalDist / 1000));
				txTotalDistUnit.setText(R.string.exercise_total_dist_3);
			}
			else {
				txTotalDist.setText(String.valueOf((int)totalDist));
				txTotalDistUnit.setText(R.string.exercise_total_dist_2);
			}
		}
	}

	private void setWaterValue() {
		if(selectedIndex >=0 && selectedIndex < dailySummaryList.size()){
			DailySummary dailySummary = dailySummaryList.get(selectedIndex);
	
			int exerciseTime = dailySummary.queryExerciseTime();
			int targetTime = dailySummary.getTargetTime();
			int exerciseTimePercent = (int) (exerciseTime * 100f / targetTime);
	
			float exerciseEnergy = dailySummary.queryExerciseEnergy();
			float targetEnergy = dailySummary.getTargetEnergy();
			int exerciseEnergyPercent = (int) (exerciseEnergy * 100f / targetEnergy);
	
			LogUtil.d("setWaterValue()\nexerciseTimePercent:" + exerciseTimePercent + "(" + exerciseTime + "/" + targetTime
					+ ")\nexerciseEnergyPercent:" + exerciseEnergyPercent + "(" + exerciseEnergy + "/" + targetEnergy + ")");
	
			int[] waterPercent = new int[] { exerciseTimePercent, exerciseEnergyPercent };
			float[] waterValue = new float[] { exerciseTime, exerciseEnergy };
			viewWaterCup.setValueInfo(waterPercent, waterValue);
		}
	}

	private void registerRingMessageReceiver() {
		if (holderActivity != null) {
			IntentFilter filter = new IntentFilter();
			filter.addAction(RingBleService.ACTION_GATT_EXERCISE_INFO_REPORT);
			holderActivity.registerReceiver(ringMessageReceiver, filter);
		}
	}

	private void unregisterRingMessageReceiver() {
		if (holderActivity != null) {
			holderActivity.unregisterReceiver(ringMessageReceiver);
		}
	}

	private final BroadcastReceiver ringMessageReceiver = new BroadcastReceiver() {
		@Override public void onReceive(Context context, Intent intent) {
			final String action = intent.getAction();
			if (RingBleService.ACTION_GATT_EXERCISE_INFO_REPORT.equals(action)) {
				notifyDataSetChanged();
			}
		}
	};
	
	
	
	private void shareToFriend() {
		final Bitmap ss = BaseUtil.takeScreenShot(holderActivity);
		new Thread(new Runnable() {
			@Override public void run() {
				if (holderActivity != null) {
					try {
						final File fdir = holderActivity.getExternalFilesDir(null);
						if (!fdir.exists()) {
							fdir.mkdir();
						}
						final File f = new File(fdir, C.app.tmp_share);
						if (!f.exists()) {
							f.createNewFile();
						}
						BaseUtil.bitmapToFile(ss, f.getAbsolutePath());
						DailySummary today = App.i().getDailySummary();
						int calories = (int) today.queryExerciseEnergy();
						final String shareContent = String.format(
								getString(R.string.share_content),
								String.valueOf(calories));
						holderActivity.runOnUiThread(new Runnable() {
							@Override public void run() {
								App.i().showShare(shareContent, f);
							}
						});
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
	}
}
